// @Author EthanScriptOn
// @Desc
package config_source_loader

import (
	"gitee.com/fatzeng/srf_switch_config/config_define"
	"regexp"
	"strings"
)

type IniFileSourceLoader struct {
	*FileBaseSourceLoader
}

func (i *IniFileSourceLoader) GetConfigSourceType() config_define.ConfigSourceType {
	return config_define.INI
}

func (i *IniFileSourceLoader) Initialization() (err error) {
	keyValuePairsSlicing := GenerateSourceLoaderSlicing("=", true, 2)
	multiKeySlicing := GenerateSourceLoaderSlicing(".", true, -1)
	i.ConfigSourceLoaderSteps, err = GenerateAllowableCutFileBaseSourceLoaderSteps(i, keyValuePairsSlicing, multiKeySlicing, `(\\w+)\\[(\\d+)\\]`)
	if err != nil {
		return err
	}
	i.FileBaseSourceLoader, err = GenerateFileBaseSourceLoader(i, i.GetConfigSourceType())
	if err != nil {
		return err
	}
	return i.FileBaseSourceLoader.Initialization()
}

func (i *IniFileSourceLoader) SplitSegment(describes []*SegmentLineDescribe) ([]Segment, error) {
	segmentLines := make([]*SegmentLineDescribe, 0)
	segments := make([]Segment, 0)
	assembly := false
	for _, describe := range describes {
		segmentCompile := regexp.MustCompile(`^\[.*?\]$`)
		if segmentCompile.MatchString(describe.originalContent) {
			assembly = true
			if len(segmentLines) != 0 {
				segments = append(segments, segmentLines)
				segmentLines = make([]*SegmentLineDescribe, 0)
			}
		} else {
			if assembly {
				segmentLines = append(segmentLines, describe)
			}
		}
	}
	return segments, nil
}

func (i *IniFileSourceLoader) IsAnnotation(line string) bool {
	return line == "" || strings.HasPrefix(line, "#")
}
